<template>
  <textarea :id="tinymceId" style="visibility: hidden" />
</template>

<script>
  import loadTinymce from '@/utils/loadTinymce'
  import {
    plugins,
    toolbar
  } from './config'
  import {
    debounce
  } from 'throttle-debounce'

  let num = 1

  export default {
    props: {
      id: {
        type: String,
        default: () => {
          num === 10000 && (num = 1)
          return `tinymce${+new Date()}${num++}`
        }
      },
      value: {
        default: ''
      }
    },
    data() {
      return {
        tinymceId: this.id
      }
    },
    mounted() {
      loadTinymce(tinymce => {
        // eslint-disable-next-line global-require
        require('./zh_CN')

        let conf = {
          selector: `#${this.tinymceId}`,
          language: 'zh_CN',
          plugins,
          toolbar,
          // 编辑器高度
          height: 650,
          min_height: 400,
          // 字体大小
          fontsize_formats: '12px 14px 16px 18px 24px 36px 48px 56px 72px',
          // 字形
          font_formats: '微软雅黑=Microsoft YaHei,Helvetica Neue,PingFang SC,sans-serif;苹果苹方=PingFang SC,Microsoft YaHei,sans-serif;宋体=simsun,serif;仿宋体=FangSong,serif;黑体=SimHei,sans-serif;Arial=arial,helvetica,sans-serif;Arial Black=arial black,avant garde;Book Antiqua=book antiqua,palatino;Comic Sans MS=comic sans ms,sans-serif;Courier New=courier new,courier;Georgia=georgia,palatino;Helvetica=helvetica;Impact=impact,chicago;Symbol=symbol;Tahoma=tahoma,arial,helvetica,sans-serif;Terminal=terminal,monaco;Times New Roman=times new roman,times;Verdana=verdana,geneva;Webdings=webdings;Wingdings=wingdings,zapf dingbats;知乎配置=BlinkMacSystemFont, Helvetica Neue, PingFang SC, Microsoft YaHei, Source Han Sans SC, Noto Sans CJK SC, WenQuanYi Micro Hei, sans-serif;小米配置=Helvetica Neue,Helvetica,Arial,Microsoft Yahei,Hiragino Sans GB,Heiti SC,WenQuanYi Micro Hei,sans-serif',
          // 默认链接
          link_list: [{
          	title: '百度',
          	value: 'http://www.baidu.com'
          }, ],
          // 默认图片
          image_list: [{
          	title: '预置图片1',
          	value: 'https://www.tiny.cloud/images/glyph-tinymce@2x.png'
          }, ],
          // 预制图片样式
          image_class_list: [{
          		title: 'None',
          		value: ''
          	},
          	{
          		title: 'Some class',
          		value: 'class-name'
          	}
          ],
          //importcss_append: true,
          // 为内容模板插件提供预置模板
          templates: [{
          		title: '模板1',
          		description: '介绍文字1',
          		content: '模板内容'
          	},
          	{
          		title: '模板2',
          		description: '介绍文字2',
          		content: '<div class="mceTmpl"><span class="cdate">CDATE</span>，<span class="mdate">MDATE</span>，我的内容</div>'
          	}
          ],
          // content_security_policy: "script-src *;",
          extended_valid_elements: 'script[src]',
          template_cdate_format: '[CDATE: %m/%d/%Y : %H:%M:%S]',
          template_mdate_format: '[MDATE: %m/%d/%Y : %H:%M:%S]',
          autosave_ask_before_unload: false,
          toolbar_mode: 'wrap',
          // 此选项可以通过空格或逗号分隔的类型名称指定允许上传的类型。
          file_picker_types: 'file image media'
        }

        // conf = Object.assign(conf, this.$attrs)

        // conf.init_instance_callback = editor => {
        //   if (this.value) editor.setContent(this.value)
        //   this.vModel(editor)
        // }

        tinymce.init(conf)
      })
    },
    destroyed() {
      this.destroyTinymce()
    },
    methods: {
      vModel(editor) {
        // 控制连续写入时setContent的触发频率
        const debounceSetContent = debounce(250, editor.setContent)
        this.$watch('value', (val, prevVal) => {
          if (editor && val !== prevVal && val !== editor.getContent()) {
            if (typeof val !== 'string') val = val.toString()
            debounceSetContent.call(editor, val)
          }
        })

        editor.on('change keyup undo redo', () => {
          this.$emit('input', editor.getContent())
        })
      },

      destroyTinymce() {
        if (!window.tinymce) return
        const tinymce = window.tinymce.get(this.tinymceId)
        if (tinymce) {
          tinymce.destroy()
        }
      }
    }
  }
</script>
